package com.issc.framework.helper;

import com.issc.framework.annotation.Autowired;
import com.issc.framework.util.ReflectionUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 找到注解为Autowired的字段，并为他赋值
 */
public class IocHelper {
    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (!beanMap.isEmpty()) {
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();

                //获取类的字段，存入Filed数组
                Field[] fields = beanClass.getDeclaredFields();
                if (!ArrayUtils.isEmpty(fields)) {
                    for (Field field : fields
                            ) {
                        if (field.isAnnotationPresent(Autowired.class)) {
                            Class<?> beanFieldClass = field.getType();
                            //创建对象
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null) {
                                //通过反射初始化field的值
                                ReflectionUtil.getField(beanInstance, field, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
